<template>
	<view class="container">
		<!-- 标题栏 -->
		<view class="page-title">创建旅行团</view>

		<!-- 表单卡片 -->
		<view class="form-card">
			<view class="form-row">
				<view class="label-wrap">
					<text class="label">团名称</text>
					<text class="required">*</text>
				</view>
				<input class="input" v-model.trim="form.groupName" placeholder="请输入团名称" />
			</view>

			<view class="form-row">
				<view class="label-wrap">
					<text class="label">行程</text>
					<text class="required">*</text>
				</view>
				<view class="picker-val flat-edit" @click="showItineraryDrawer = true">
					<text class="edit-value">{{ selectedItineraryText }}</text>
					<image src="/static/icons/edit.png" class="edit-icon" mode="aspectFit" />
				</view>
			</view>

			<view class="form-row">
				<view class="label-wrap">
					<text class="label">团状态</text>
				</view>
				<picker mode="selector" :range="statusOptions" @change="onStatusChange" @click.prevent>
					<view class="picker-val">{{ selectedStatusText }}</view>
				</picker>
			</view>

			<view class="form-row">
				<view class="label-wrap">
					<text class="label">目的地</text>
				</view>
				<input class="input" v-model.trim="form.destination" placeholder="请输入目的地" />
			</view>

			<view class="form-row">
				<view class="label-wrap">
					<text class="label">开始日期</text>
					<text class="required">*</text>
				</view>
				<picker mode="date" @change="handleStartDateChange" @click.prevent>
					<view class="picker-val">{{ form.startDate || '选择日期' }}</view>
				</picker>
			</view>

			<view class="form-row">
				<view class="label-wrap">
					<text class="label">结束日期</text>
				</view>
				<picker mode="date" @change="handleEndDateChange" @click.prevent>
					<view class="picker-val">{{ form.endDate || '选择日期' }}</view>
				</picker>
			</view>



			<!-- 导游选择 - 只有同时有开始和结束时间且有导游数据时才显示 -->
			<view class="form-row" v-if="form.startDate && form.endDate && guides.length > 1">
				<view class="label-wrap">
					<text class="label">导游</text>
				</view>
				<view class="picker-val flat-edit"
					@click="form.endDate ? showGuideDrawer = true : uni.showToast({title: '请先设置结束日期', icon: 'none'})">
					<text class="edit-value">{{ selectedGuideText }}</text>
					<image src="/static/icons/edit.png" class="edit-icon" mode="aspectFit" />
				</view>
			</view>



			<view class="form-row">
				<view class="label-wrap">
					<text class="label">成团人数上限</text>
				</view>
				<input class="input" type="number" v-model.number="form.capacity" placeholder="请输入人数上限"
					@input="loadVehiclesList" />
			</view>
			<!-- 车辆选择 - 只有同时有开始和结束时间且有团人数且有车辆数据时才显示 -->
			<view class="form-row" v-if="form.startDate && form.endDate && form.capacity > 0 && vehicles.length > 1">
				<view class="label-wrap">
					<text class="label">车辆选择</text>
				</view>
				<view class="picker-val flat-edit" @click="showVehicleDrawer = true">
					<text class="edit-value">{{ selectedVehicleText }}</text>
					<image src="/static/icons/edit.png" class="edit-icon" mode="aspectFit" />
				</view>
			</view>
			<view class="form-row">
				<view class="label-wrap">
					<text class="label">单价（元/人）</text>
				</view>
				<input class="input" type="number" v-model.number="form.price" placeholder="请输入单价" />
			</view>

			<view class="form-row form-row-textarea">
				<view class="label-wrap label-wrap-textarea">
					<text class="label">行程描述</text>
				</view>
				<textarea class="textarea" v-model.trim="form.itinerary" placeholder="请输入行程描述（可选）"></textarea>
			</view>
		</view>

		<view class="actions">
			<button class="save-btn" @click="submit" :disabled="submitting">{{ submitting ? '创建中...' : '创建团' }}</button>
		</view>

		<!-- 导游选择抽屉 -->
		<view class="drawer guide-drawer flat-drawer" :class="{ show: showGuideDrawer }" @touchmove.stop>
			<view class="drawer-header flat-drawer-header">
				<text class="drawer-title">选择导游</text>
				<image src="/static/icons/close.png" class="drawer-close" mode="aspectFit" @click="closeGuideDrawer" />
			</view>
			<view class="drawer-search">
				<input class="search-input" v-model="guideSearchText" placeholder="搜索导游名称" />
			</view>
			<view class="drawer-body flat-drawer-body">
				<view v-if="filteredGuides.length > 0" class="drawer-item flat-drawer-item"
					v-for="(guide, idx) in filteredGuides" :key="idx"
					:class="{ active: form.guideId === filteredGuideIds[idx] }" @click="selectGuide(idx, true)">
					<text class="item-name">{{ guide }}</text>
					<image v-if="form.guideId === filteredGuideIds[idx]" src="/static/icons/selected.png"
						class="item-selected" mode="aspectFit" />
				</view>
				<view v-else class="no-result">
					<text>未找到匹配的导游</text>
				</view>
			</view>
		</view>

		<!-- 行程选择抽屉 -->
		<view class="drawer itinerary-drawer flat-drawer" :class="{ show: showItineraryDrawer }" @touchmove.stop>
			<view class="drawer-header flat-drawer-header">
				<text class="drawer-title">选择行程</text>
				<image src="/static/icons/close.png" class="drawer-close" mode="aspectFit"
					@click="closeItineraryDrawer" />
			</view>
			<view class="drawer-search">
				<input class="search-input" v-model="itinerarySearchText" placeholder="搜索行程名称" />
			</view>
			<view class="drawer-body flat-drawer-body">
				<view v-if="filteredItineraries.length > 0" class="drawer-item flat-drawer-item"
					v-for="(itinerary, idx) in filteredItineraries" :key="idx"
					:class="{ active: form.itineraryId === filteredItineraryIds[idx] }"
					@click="selectItinerary(idx, true)">
					<text class="item-name">{{ itinerary }}</text>
					<image v-if="form.itineraryId === filteredItineraryIds[idx]" src="/static/icons/selected.png"
						class="item-selected" mode="aspectFit" />
				</view>
				<view v-else class="no-result">
					<text>未找到匹配的行程</text>
				</view>
			</view>
		</view>


		<!-- 车辆选择抽屉 -->
		<view class="drawer vehicle-drawer flat-drawer" :class="{ show: showVehicleDrawer }" @touchmove.stop>
			<view class="drawer-header flat-drawer-header">
				<text class="drawer-title">选择车辆</text>
				<image src="/static/icons/close.png" class="drawer-close" mode="aspectFit"
					@click="closeVehicleDrawer" />
			</view>
			<view class="drawer-search">
				<input class="search-input" v-model="vehicleSearchText" placeholder="搜索车辆信息" />
			</view>
			<view class="drawer-body flat-drawer-body">
				<view v-if="filteredVehicles.length > 0" v-for="(vehicle, idx) in filteredVehicles" :key="idx"
					class="drawer-item flat-drawer-item vehicle-item"
					:class="{ active: form.vehicleId === filteredVehicleIds[idx] }" @click="selectVehicle(idx, true)">
					<!-- 车辆信息容器 -->
					<view class="vehicle-content">
						<!-- 车辆主信息 - 一行展示 -->
						<view class="vehicle-main-info">
							<text class="vehicle-title">{{ vehicle }}</text>
						</view>
						<!-- 车辆详细信息（如果有） -->
						<view v-if="filteredVehicleDetails[idx] && filteredVehicleDetails[idx].licensePlate"
							class="vehicle-info-details">
							<text class="vehicle-detail-item">
								<text class="detail-label">车牌号:</text>
								<text
									class="detail-value">{{ filteredVehicleDetails[idx].licensePlate || '未提供' }}</text>
							</text>
							<text class="vehicle-detail-item">
								<text class="detail-label">司机:</text>
								<text class="detail-value">{{ filteredVehicleDetails[idx].driverName || '未指定' }}</text>
							</text>
							<text class="vehicle-detail-item">
								<text class="detail-label">电话:</text>
								<text class="detail-value">{{ filteredVehicleDetails[idx].driverPhone || '未提供' }}</text>
							</text>
							<!-- 显示载客量信息 -->
							<text v-if="filteredVehicleDetails[idx].loadCapacity" class="vehicle-detail-item">
								<text class="detail-label">载客量:</text>
								<text class="detail-value">{{ filteredVehicleDetails[idx].loadCapacity }}人</text>
							</text>
						</view>
					</view>
					<!-- 选中标记 -->
					<image v-if="form.vehicleId === filteredVehicleIds[idx]" src="/static/icons/selected.png"
						class="item-selected" mode="aspectFit" />
				</view>
				<view v-else class="no-result">
					<text>未找到匹配的车辆</text>
				</view>
			</view>
		</view>

		<!-- 抽屉遮罩 -->
		<view class="drawer-mask flat-mask"
			:class="{ show: showGuideDrawer || showItineraryDrawer || showVehicleDrawer }" @click="closeAllDrawers">
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		computed
	} from 'vue'
	import http from '@/https/http.js'
	import {
		GetSelectList as getGuideSelectList
	} from '@/https/guide.js'
	import {
		GetSelectList as getItinerarySelectList
	} from '@/https/itinerary.js'
	import {
		GetSelectList as getVehicleSelectList
	} from '@/https/vehicle.js'

	const submitting = ref(false)

	const form = ref({
		groupName: '',
		itineraryId: null,
		destination: '',
		startDate: '',
		endDate: '',
		capacity: 0,
		status: 0,
		guideId: null,
		groupType: 0,
		price: 0,
		itinerary: '',
		vehicleId: null
	})

	// 下拉/抽屉数据
	const guides = ref(['请选择导游'])
	const guideIds = ref([null])
	const selectedGuideText = ref('请选择导游')
	const showGuideDrawer = ref(false)
	const guideSearchText = ref('')

	// 车辆相关
	const vehicles = ref(['请选择车辆'])
	const vehicleIds = ref([null])
	const vehicleDetails = ref([null]) // 存储完整的车辆详情
	const selectedVehicleText = ref('请选择车辆')
	const showVehicleDrawer = ref(false)
	const vehicleSearchText = ref('')

	const itineraries = ref(['请选择行程'])
	const itineraryIds = ref([null])
	const itineraryDetails = ref([null]) // 存储行程完整信息
	const selectedItineraryText = ref('请选择行程')
	const showItineraryDrawer = ref(false)
	const itinerarySearchText = ref('')

	// 过滤后的导游列表
	const filteredGuides = computed(() => {
		if (!guideSearchText.value) return guides.value;
		const searchText = guideSearchText.value.toLowerCase();
		return guides.value.filter(guide =>
			guide.toLowerCase().includes(searchText)
		);
	});

	// 过滤后的导游ID列表
	const filteredGuideIds = computed(() => {
		if (!guideSearchText.value) return guideIds.value;
		const searchText = guideSearchText.value.toLowerCase();
		return guides.value
			.map((guide, idx) => ({
				guide,
				id: guideIds.value[idx],
				index: idx
			}))
			.filter(item => item.guide.toLowerCase().includes(searchText))
			.map(item => item.id);
	});

	// 过滤后的行程列表
	const filteredItineraries = computed(() => {
		if (!itinerarySearchText.value) return itineraries.value;
		const searchText = itinerarySearchText.value.toLowerCase();
		return itineraries.value.filter(itinerary =>
			itinerary.toLowerCase().includes(searchText)
		);
	});

	// 过滤后的行程ID列表
	const filteredItineraryIds = computed(() => {
		if (!itinerarySearchText.value) return itineraryIds.value;
		const searchText = itinerarySearchText.value.toLowerCase();
		return itineraries.value
			.map((itinerary, idx) => ({
				itinerary,
				id: itineraryIds.value[idx],
				index: idx
			}))
			.filter(item => item.itinerary.toLowerCase().includes(searchText))
			.map(item => item.id);
	});

	// 过滤后的行程详情列表
	const filteredItineraryDetails = computed(() => {
		if (!itinerarySearchText.value) return itineraryDetails.value;
		const searchText = itinerarySearchText.value.toLowerCase();
		return itineraries.value
			.map((itinerary, idx) => ({
				itinerary,
				detail: itineraryDetails.value[idx],
				index: idx
			}))
			.filter(item => item.itinerary.toLowerCase().includes(searchText))
			.map(item => item.detail);
	})

	// 过滤后的车辆列表
	const filteredVehicles = computed(() => {
		if (!vehicleSearchText.value) return vehicles.value;
		const searchText = vehicleSearchText.value.toLowerCase();
		return vehicles.value.filter(vehicle =>
			vehicle.toLowerCase().includes(searchText)
		);
	});

	// 过滤后的车辆ID列表
	const filteredVehicleIds = computed(() => {
		if (!vehicleSearchText.value) return vehicleIds.value;
		const searchText = vehicleSearchText.value.toLowerCase();
		return vehicles.value
			.map((vehicle, idx) => ({
				vehicle,
				id: vehicleIds.value[idx],
				index: idx
			}))
			.filter(item => item.vehicle.toLowerCase().includes(searchText))
			.map(item => item.id);
	});

	// 过滤后的车辆详情列表
	const filteredVehicleDetails = computed(() => {
		if (!vehicleSearchText.value) return vehicleDetails.value;
		const searchText = vehicleSearchText.value.toLowerCase();
		return vehicles.value
			.map((vehicle, idx) => ({
				vehicle,
				detail: vehicleDetails.value[idx],
				index: idx
			}))
			.filter(item => item.vehicle.toLowerCase().includes(searchText))
			.map(item => item.detail);
	});

	const groupTypeOptions = ref(['国内游', '国外游', '周边游'])
	const selectedGroupTypeText = ref(groupTypeOptions.value[0])

	const statusOptions = ref(['招募中', '已成团', '已出发', '已结束', '已取消'])
	const selectedStatusText = ref(statusOptions.value[0])

	onMounted(async () => {
		// 加载行程列表 - 只使用接口返回的数据
		try {
			const itineraryList = await getItinerarySelectList()
			console.log('获取到的行程列表:', itineraryList)
			if (Array.isArray(itineraryList) && itineraryList.length > 0) {

				// 处理行程数据，确保正确提取行程名称
				itineraries.value = itineraryList.map((item, index) => {
					if (!item || typeof item !== 'object') {
						console.log(`第${index}个行程项不是有效的对象`)
						return '未知行程'
					}
					// 尝试所有可能的行程名称字段
					return item.itineraryName || '未知行程'
				})

				// 提取行程ID
				itineraryIds.value = itineraryList.map(item => {
					return item.itineraryId || null
				})

				// 存储完整行程信息用于后续提取目的地
				itineraryDetails.value = itineraryList

			} else {
				console.log('行程列表为空或格式不正确')
				// 空数据情况，不使用默认模拟数据
				itineraries.value = ['请选择行程']
				itineraryIds.value = [null]
				itineraryDetails.value = [null]
			}
		} catch (e) {
			console.warn('加载行程失败:', e)
			// 异常情况下保持空数据状态
			itineraries.value = ['请选择行程']
			itineraryIds.value = [null]
			itineraryDetails.value = [null]
		}

	})

	const selectGuide = (idx, isFiltered = false) => {
		if (isFiltered) {
			form.value.guideId = filteredGuideIds.value[idx] || null
			selectedGuideText.value = filteredGuides.value[idx] || '请选择导游'
		} else {
			form.value.guideId = guideIds.value[idx] || null
			selectedGuideText.value = guides.value[idx] || '请选择导游'
		}
		showGuideDrawer.value = false
		guideSearchText.value = ''
	}

	const selectItinerary = (idx, isFiltered = false) => {
		let selectedId, selectedName, selectedDetail

		if (isFiltered) {
			selectedId = filteredItineraryIds.value[idx] || null
			selectedName = filteredItineraries.value[idx] || '请选择行程'
		} else {
			selectedId = itineraryIds.value[idx] || null
			selectedName = itineraries.value[idx] || '请选择行程'
		}

		// 更新表单数据
		form.value.itineraryId = selectedId
		selectedItineraryText.value = selectedName

		// 根据选择的行程ID在原始行程列表中查找对应的行程详情，提取目的地信息
		console.log('选择的行程ID:', selectedId)
		console.log(itineraryDetails)
		var destination = "";
		var itinerary_day = 0;
		// 如果直接获取失败，尝试在原始行程列表中查找
		if (itineraryDetails.value && itineraryDetails.value.length > 0) {
			const matchedItinerary = itineraryDetails.value.find(item => {
				if (item.itineraryId === selectedId) {
					destination = item.destination;
					itinerary_day = item.days || 0;
					console.log(itinerary_day)
				}
			})
		}

		// 如果行程有天数且已选择开始时间，自动计算结束时间
		if (itinerary_day > 0 && form.value.startDate) {
			const startDate = new Date(form.value.startDate);
			const endDate = new Date(startDate);
			endDate.setDate(startDate.getDate() + itinerary_day - 1); // 减1是因为开始日期算第一天

			// 格式化结束日期为YYYY-MM-DD格式
			const year = endDate.getFullYear();
			const month = String(endDate.getMonth() + 1).padStart(2, '0');
			const day = String(endDate.getDate()).padStart(2, '0');
			form.value.endDate = `${year}-${month}-${day}`;
			console.log('根据行程天数自动计算结束时间:', form.value.endDate);
		}

		// 更新目的地字段
		if (destination) {
			form.value.destination = destination
			console.log('从行程详情提取目的地:', destination)
		}

		// 关闭抽屉
		showItineraryDrawer.value = false
		itinerarySearchText.value = ''
	}

	const closeGuideDrawer = () => {
		showGuideDrawer.value = false
		guideSearchText.value = ''
	}
	const closeItineraryDrawer = () => {
		showItineraryDrawer.value = false
		itinerarySearchText.value = ''
	}

	const closeAllDrawers = () => {
		showGuideDrawer.value = false
		showItineraryDrawer.value = false
		showVehicleDrawer.value = false
		guideSearchText.value = ''
		itinerarySearchText.value = ''
		vehicleSearchText.value = ''
	}

	// 处理开始日期选择变化
	const handleStartDateChange = (e) => {
		// 设置开始日期
		form.value.startDate = e.detail.value;
		console.log('选择的开始日期:', form.value.startDate);

		// 如果已选择行程且行程ID有效，尝试获取行程天数
		if (form.value.itineraryId) {
			let itinerary_day = 0;
			// 在行程详情中查找对应的行程信息
			if (itineraryDetails.value && itineraryDetails.value.length > 0) {
				const matchedItinerary = itineraryDetails.value.find(item => item.itineraryId === form.value
					.itineraryId);
				if (matchedItinerary && matchedItinerary.days) {
					itinerary_day = Number(matchedItinerary.days) || 0;
					console.log('获取到的行程天数:', itinerary_day);
				}
			}

			// 如果行程有天数，自动计算结束时间
			if (itinerary_day > 0) {
				const startDate = new Date(form.value.startDate);
				const endDate = new Date(startDate);
				endDate.setDate(startDate.getDate() + itinerary_day - 1); // 减1是因为开始日期算第一天

				// 格式化结束日期为YYYY-MM-DD格式
				const year = endDate.getFullYear();
				const month = String(endDate.getMonth() + 1).padStart(2, '0');
				const day = String(endDate.getDate()).padStart(2, '0');
				form.value.endDate = `${year}-${month}-${day}`;
				console.log('根据行程天数自动计算结束时间:', form.value.endDate);

				// 自动计算结束时间后，立即加载导游列表，修复导游选择框不显示的bug
				if (form.value.startDate && form.value.endDate) {
					loadGuidesList();
				}
			}
		}

	}

	// 处理结束日期选择变化
	const handleEndDateChange = (e) => {
		// 设置结束日期
		form.value.endDate = e.detail.value;
		console.log('选择的结束日期:', form.value.endDate);

		// 只有同时有开始和结束日期时才加载导游列表
		if (form.value.startDate && form.value.endDate) {
			loadGuidesList();
		}
	};

	// 加载导游列表
	const loadGuidesList = async () => {
		// 只有同时有开始和结束日期时才加载导游列表
		if (!form.value.startDate || !form.value.endDate) return;

		try {
			// 构建符合Mini_carOpenid格式的参数
			const params = {
				OpenId: 0, // 小程序请求者的OpenId
				StartDate: form.value.startDate ? new Date(form.value.startDate) : null,
				EndDate: new Date(form.value.endDate)
			};

			const guideList = await getGuideSelectList(params);
			if (Array.isArray(guideList) && guideList.length > 0) {
				guides.value = guideList.map(item => item.Label);
				guideIds.value = guideList.map(item => item.Value);
			}
		} catch (e) {
			console.warn('加载导游失败', e);
			uni.showToast({
				title: '加载导游列表失败',
				icon: 'none'
			});
		}
	};

	// 加载车辆列表
	const loadVehiclesList = async () => {
		// 只有同时有开始和结束日期以及团人数时才加载车辆列表
		if (!form.value.startDate || !form.value.endDate || !form.value.capacity || form.value.capacity <= 0)
			return;

		try {
			// 构建符合Mini_carOpenid格式的参数
			const params = {
				OpenId: 0, // 小程序请求者的OpenId
				StartDate: form.value.startDate ? new Date(form.value.startDate) : null,
				EndDate: new Date(form.value.endDate),
				count: form.value.capacity // 团人数
			};

			const vehicleList = await getVehicleSelectList(params);
			console.log('获取到的车辆列表原始数据:', vehicleList);
			if (Array.isArray(vehicleList) && vehicleList.length > 0) {
				// 存储完整的车辆信息
				vehicleDetails.value = vehicleList;
				// 格式化显示的车辆文本，包含车牌号、车型、载客量等信息
				vehicles.value = vehicleList.map(item => {
					const vehicle = item;
					// 根据返回的数据结构格式化显示文本
					if (vehicle.licensePlate) {
						return `${vehicle.licensePlate} - ${vehicle.vehicleType || '未知车型'} - 核载${vehicle.loadCapacity || 0}人`;
					} else if (item.Label) {
						return item.Label;
					}
					return '未知车辆';
				});
				// 确保vehicleIds数组中包含vehicleId字段，优先使用vehicleId
				vehicleIds.value = vehicleList.map(item => {
					const vehicleId = item.vehicleId || item.Value;
					console.log('车辆ID处理:', {
						原始ID: item.Value,
						vehicleId: item.vehicleId,
						最终使用: vehicleId
					});
					return vehicleId;
				});
			}
		} catch (e) {
			console.warn('加载车辆失败', e);
			uni.showToast({
				title: '加载车辆列表失败',
				icon: 'none'
			});
		}
	};

	const selectVehicle = (idx, isFiltered = false) => {
		// 记录选择前的车辆ID
		console.log('选择前的vehicleId:', form.value.vehicleId);

		let selectedId, selectedName, selectedDetail;
		if (isFiltered) {
			selectedId = filteredVehicleIds.value[idx] || null;
			selectedName = filteredVehicles.value[idx] || '请选择车辆';
			selectedDetail = filteredVehicleDetails.value[idx];
			// 记录筛选列表中的车辆信息
			console.log('从筛选列表选择车辆:', {
				索引: idx,
				车辆ID: selectedId,
				车辆名称: selectedName,
				车辆详情: selectedDetail,
				vehicleId字段: selectedDetail?.vehicleId,
				Value字段: selectedDetail?.Value
			});
		} else {
			selectedId = vehicleIds.value[idx] || null;
			selectedName = vehicles.value[idx] || '请选择车辆';
			selectedDetail = vehicleDetails.value[idx];
			// 记录原始列表中的车辆信息
			console.log('从原始列表选择车辆:', {
				索引: idx,
				车辆ID: selectedId,
				车辆名称: selectedName,
				车辆详情: selectedDetail,
				vehicleId字段: selectedDetail?.vehicleId,
				Value字段: selectedDetail?.Value
			});
		}

		// 再次确认车辆ID，如果有vehicleId字段则优先使用
		const finalVehicleId = selectedDetail?.vehicleId || selectedId || null;
		console.log('最终确认的车辆ID:', finalVehicleId);

		// 更新表单数据
		form.value.vehicleId = finalVehicleId;
		selectedVehicleText.value = selectedName;

		// 记录选择后的车辆ID
		console.log('选择后的vehicleId:', form.value.vehicleId);
		console.log('完整表单车辆信息:', {
			vehicleId: form.value.vehicleId,
			selectedVehicleText: selectedVehicleText.value
		});

		showVehicleDrawer.value = false
		vehicleSearchText.value = ''
	};

	const closeVehicleDrawer = () => {
		showVehicleDrawer.value = false
		vehicleSearchText.value = ''
	};;

	const onStatusChange = (e) => {
		const idx = e.detail.value
		form.value.status = parseInt(idx, 10) || 0
		selectedStatusText.value = statusOptions.value[idx] || statusOptions.value[0]
	}

	const validate = () => {
		if (!form.value.groupName) {
			uni.showToast({
				title: '请输入团名称',
				icon: 'none'
			});
			return false
		}
		if (!form.value.itineraryId) {
			uni.showToast({
				title: '请选择行程',
				icon: 'none'
			});
			return false
		}
		if (!form.value.startDate) {
			uni.showToast({
				title: '请选择开始日期',
				icon: 'none'
			});
			return false
		}
		if (!form.value.endDate) {
			uni.showToast({
				title: '请选择结束日期',
				icon: 'none'
			});
			return false
		}
		// 验证结束日期不能早于开始日期
		if (form.value.startDate > form.value.endDate) {
			uni.showToast({
				title: '结束日期不能早于开始日期',
				icon: 'none'
			});
			return false;
		}
		// 验证容量为正整数
		if (form.value.capacity < 1) {
			uni.showToast({
				title: '请输入有效的成团人数上限',
				icon: 'none'
			});
			return false;
		}
		return true
	}

	const submit = async () => {
		if (!validate()) return
		if (submitting.value) return
		submitting.value = true
		uni.showLoading({
			title: '创建中...'
		})
		try {
			// 格式化日期为DateTime格式
			const formatDate = (dateString) => {
				if (!dateString) return null;
				return dateString + 'T00:00:00';
			}

			const payload = {
				openId: 0, // 小程序请求者的OpenId（必填）
				groupName: form.value.groupName,
				startDate: formatDate(form.value.startDate),
				endDate: formatDate(form.value.endDate),
				status: form.value.status || 0,
				capacity: form.value.capacity || 0,
				groupType: form.value.groupType || 0,
				price: Number(form.value.price || 0).toFixed(2), // 转换为decimal类型
				destination: form.value.destination,
				itineraryId: form.value.itineraryId,
				itinerary: form.value.itinerary,
				guideId: form.value.guideId || null,
				vehicleId: form.value.vehicleId || null
			};
			console.log('提交的车辆ID:', form.value.vehicleId);
			console.log('完整提交数据:', payload);

			const res = await http.post('Mini/TourGroup/Create', payload)
			let newId = null
			if (res && typeof res === 'object') {
				newId = res.id || (res.data && res.data.id) || null
			}

			uni.showToast({
				title: '创建成功',
				icon: 'success'
			})
			setTimeout(() => {
				if (newId) {
					uni.navigateTo({
						url: `/pages/groups/tourGroupDetail?groupId=${encodeURIComponent(String(newId))}`
					})
				} else {
					uni.navigateBack()
				}
			}, 600)
		} catch (err) {
			console.error('创建团失败', err)
			uni.showToast({
				title: '创建失败',
				icon: 'none'
			})
		} finally {
			submitting.value = false
			uni.hideLoading()
		}
	}
</script>

<style scoped>
	/* 基础样式 */
	.container {
		padding: 24rpx;
		background-color: #f0f7ff;
		min-height: 100vh;
	}

	/* 页面标题 */
	.page-title {
		font-size: 38rpx;
		font-weight: 700;
		color: #165DFF;
		text-align: center;
		margin: 30rpx 0 40rpx;
		padding-bottom: 20rpx;
		border-bottom: 1px solid rgba(22, 93, 255, 0.1);
	}

	/* 表单卡片 - 增加质感和阴影 */
	.form-card {
		background: linear-gradient(145deg, #ffffff, #f0f7ff);
		border-radius: 20rpx;
		padding: 40rpx 30rpx;
		box-shadow: 0 8rpx 24rpx rgba(22, 93, 255, 0.08);
		margin-bottom: 30rpx;
	}

	/* 表单行样式 - 垂直排列 */
	.form-row {
		flex-direction: column;
		/* 垂直排列 */
		align-items: flex-start;
		/* 左对齐 */
		margin-bottom: 20rpx;
		/* 缩短底部外边距（原40rpx） */
		padding-bottom: 20rpx;
		/* 缩短底部内边距（原40rpx） */
		border-bottom: 1rpx solid rgba(22, 93, 255, 0.08);
		transition: all 0.3s ease;
	}

	.form-row:last-child {
		border-bottom: none;
		margin-bottom: 0;
		padding-bottom: 0;
	}

	/* 文本域行特殊处理（保持与其他行一致的紧凑感） */
	.form-row-textarea {
		align-items: flex-start;
		/* 继承上面的margin和padding，无需额外设置 */
	}

	/* 标签样式 - 占满一行 */
	.label-wrap {
		width: 100%;
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;
		/* 与输入区域保持间距 */
	}

	.label-wrap-textarea {
		padding-top: 0;
		margin-bottom: 16rpx;
	}

	.label {
		font-size: 30rpx;
		color: #1D2129;
		font-weight: 600;
	}

	.required {
		color: #165DFF;
		font-size: 32rpx;
		margin-left: 6rpx;
	}

	/* 输入框样式 - 自适应宽度调整 */
	.input {
		width: auto;
		/* 自适应内容宽度 */
		min-width: 300rpx;
		/* 最小宽度保证美观 */
		max-width: 100%;
		/* 最大不超过父容器 */
		padding: 20rpx 24rpx;
		border-radius: 12rpx;
		background: #ffffff;
		border: 1.5rpx solid #E5E6EB;
		font-size: 28rpx;
		color: #1D2129;
		transition: all 0.3s ease;
		box-shadow: inset 0 1rpx 3rpx rgba(0, 0, 0, 0.03);
	}

	.input:focus {
		border-color: #165DFF;
		box-shadow: 0 0 0 5rpx rgba(22, 93, 255, 0.1);
		outline: none;
	}

	.input::placeholder {
		color: #86909C;
		font-size: 28rpx;
	}

	/* 选择器样式 - 自适应宽度 */
	.picker-val {
		width: auto;
		/* 自适应内容宽度 */
		min-width: 300rpx;
		/* 最小宽度保证美观 */
		max-width: 100%;
		/* 最大不超过父容器 */
		padding: 20rpx 24rpx;
		background: #ffffff;
		border-radius: 12rpx;
		border: 1.5rpx solid #E5E6EB;
		font-size: 28rpx;
		color: #1D2129;
		display: flex;
		align-items: center;
		justify-content: space-between;
		transition: all 0.3s ease;
	}

	.picker-val:active {
		background-color: #f5f8ff;
	}

	/* 文本域样式 - 保持满宽更适合多行输入 */
	.textarea {
		min-height: 180rpx;
		padding: 20rpx 24rpx;
		background: #ffffff;
		border-radius: 12rpx;
		border: 1.5rpx solid #E5E6EB;
		font-size: 28rpx;
		color: #1D2129;
		line-height: 1.6;
		resize: none;
		transition: all 0.3s ease;
		box-shadow: inset 0 1rpx 3rpx rgba(0, 0, 0, 0.03);
	}

	.textarea:focus {
		border-color: #165DFF;
		box-shadow: 0 0 0 5rpx rgba(22, 93, 255, 0.1);
		outline: none;
	}

	.textarea::placeholder {
		color: #86909C;
		font-size: 28rpx;
	}

	/* 操作按钮区 */
	.actions {
		margin-top: 50rpx;
		padding: 0 10rpx;
	}

	/* 按钮样式 - 蓝色渐变和质感 */
	.save-btn {
		width: 100%;
		background: linear-gradient(135deg, #165DFF, #0E42D2);
		color: #fff;
		padding: 24rpx 0;
		border-radius: 14rpx;
		font-size: 34rpx;
		font-weight: 600;
		border: none;
		transition: all 0.3s ease;
		box-shadow: 0 6rpx 16rpx rgba(22, 93, 255, 0.3);
		position: relative;
		overflow: hidden;
	}

	.save-btn::after {
		content: '';
		position: absolute;
		top: 0;
		left: -100%;
		width: 100%;
		height: 100%;
		background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
		transition: all 0.6s ease;
	}

	.save-btn:active {
		background: linear-gradient(135deg, #0E42D2, #165DFF);
		transform: translateY(2rpx);
		box-shadow: 0 4rpx 12rpx rgba(22, 93, 255, 0.25);
	}

	.save-btn:hover::after {
		left: 100%;
	}

	/* 编辑区域样式 */
	.flat-edit {
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

	.edit-value {
		font-size: 28rpx;
		color: #1D2129;
		flex: 1;
		text-align: left;
	}

	.edit-icon {
		width: 30rpx;
		height: 30rpx;
		color: #165DFF;
		opacity: 0.7;
		transition: all 0.2s ease;
	}

	.edit-icon:active {
		opacity: 1;
		transform: scale(0.9);
	}

	/* 抽屉样式优化 - 蓝色主题 */
	.flat-drawer {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background: #ffffff;
		border-top-left-radius: 30rpx;
		border-top-right-radius: 30rpx;
		transform: translateY(100%);
		transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1);
		z-index: 999;
		max-height: 70vh;
		box-shadow: 0 -6rpx 24rpx rgba(22, 93, 255, 0.12);
	}

	.flat-drawer.show {
		transform: translateY(0);
	}

	.flat-drawer-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 28rpx 36rpx;
		border-bottom: 1rpx solid rgba(22, 93, 255, 0.1);
		background-color: #f5f8ff;
		border-top-left-radius: 30rpx;
		border-top-right-radius: 30rpx;
	}

	.drawer-title {
		font-size: 36rpx;
		font-weight: 600;
		color: #165DFF;
	}

	.drawer-close {
		width: 48rpx;
		height: 48rpx;
		padding: 8rpx;
		transition: all 0.2s ease;
	}

	.drawer-close:active {
		transform: rotate(90deg) scale(0.9);
	}

	/* 搜索框样式 */
	.drawer-search {
		padding: 20rpx 36rpx;
		border-bottom: 1rpx solid rgba(22, 93, 255, 0.1);
		background-color: #fafafa;
	}

	.search-input {
		width: 100%;
		padding: 20rpx 24rpx;
		background: #ffffff;
		border-radius: 12rpx;
		border: 1.5rpx solid #E5E6EB;
		font-size: 28rpx;
		color: #1D2129;
	}

	.search-input::placeholder {
		color: #86909C;
	}

	.flat-drawer-body {
		padding: 10rpx 0;
		max-height: calc(70vh - 200rpx);
		overflow-y: auto;
	}

	/* 无结果提示样式 */
	.no-result {
		padding: 60rpx 36rpx;
		text-align: center;
		color: #86909C;
		font-size: 28rpx;
	}

	.drawer-item {
		padding: 28rpx 36rpx;
		border-bottom: 1rpx solid rgba(22, 93, 255, 0.08);
		display: flex;
		justify-content: space-between;
		align-items: center;
		transition: all 0.3s ease;
	}

	.drawer-item:active {
		background-color: #f0f7ff;
	}

	.drawer-item.active {
		background-color: #e8f3ff;
		color: #165DFF;
	}

	.item-name {
		font-size: 32rpx;
	}

	/* 车辆详情信息样式 */
	.vehicle-item {
		padding: 24rpx 36rpx;
		border-bottom: 1rpx solid rgba(22, 93, 255, 0.08);
		transition: all 0.3s ease;
		position: relative;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.vehicle-item:last-child {
		border-bottom: none;
	}

	.vehicle-item:active {
		background-color: #f0f7ff;
	}

	.vehicle-item.active {
		background-color: #e8f3ff;
		color: #165DFF;
	}

	.vehicle-content {
		flex: 1;
		width: calc(100% - 60rpx);
		/* 为选中标记留出空间 */
	}

	.vehicle-main-info {
		display: flex;
		align-items: center;
		justify-content: space-between;
		width: 100%;
		margin-bottom: 8rpx;
	}

	.vehicle-title {
		font-size: 30rpx;
		font-weight: 500;
		color: #1D2129;
		flex: 1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		margin-right: 12rpx;
	}

	.vehicle-item.active .vehicle-title {
		color: #165DFF;
		font-weight: 600;
	}

	.vehicle-info-details {
		margin-top: 12rpx;
		padding-top: 16rpx;
		border-top: 1rpx solid rgba(22, 93, 255, 0.08);
		display: flex;
		flex-direction: column;
		gap: 10rpx;
	}

	.vehicle-detail-item {
		font-size: 26rpx;
		color: #666666;
		line-height: 1.6;
	}

	.vehicle-item.active .vehicle-detail-item {
		color: #4E6AF1;
	}

	.detail-label {
		color: #86909C;
		font-weight: 500;
		margin-right: 6rpx;
	}

	.detail-value {
		color: inherit;
		font-weight: 400;
		word-break: break-all;
	}

	/* 车辆抽屉专属样式 */
	.vehicle-drawer .flat-drawer-header {
		background: linear-gradient(135deg, #165DFF, #0E42D2);
		color: #ffffff;
		border-bottom: none;
	}

	.vehicle-drawer .drawer-title {
		color: #ffffff;
		font-size: 38rpx;
	}

	.vehicle-drawer .drawer-close {
		background-color: rgba(255, 255, 255, 0.2);
		border-radius: 50%;
		tint-color: #ffffff;
	}

	.vehicle-drawer .drawer-search {
		padding: 20rpx 36rpx;
		background-color: #f7f9fc;
		border-bottom: 1rpx solid rgba(22, 93, 255, 0.08);
	}

	.vehicle-drawer .search-input {
		background-color: #ffffff;
		border: 1.5rpx solid rgba(22, 93, 255, 0.2);
	}

	.vehicle-drawer .flat-drawer-body {
		padding: 10rpx 0 20rpx;
		max-height: calc(70vh - 220rpx);
	}

	/* 选中标记样式 */
	.vehicle-drawer .item-selected {
		position: absolute;
		right: 36rpx;
		top: 50%;
		transform: translateY(-50%);
		width: 44rpx;
		height: 44rpx;
		tint-color: #165DFF;
	}

	.item-selected {
		width: 40rpx;
		height: 40rpx;
		tint-color: #165DFF;
	}

	/* 遮罩样式 */
	.flat-mask {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.4);
		z-index: 998;
		opacity: 0;
		transition: opacity 0.3s ease;
		pointer-events: none;
	}

	.flat-mask.show {
		opacity: 1;
		pointer-events: auto;
	}

	/* 防止遮罩层滑动 */
	.flat-mask.show {
		touch-action: none;
	}

	/* 禁用状态样式 */
	.input:disabled,
	.textarea:disabled,
	.picker-val.disabled {
		background-color: #f5f7fa;
		color: #86909C;
		border-color: #E5E6EB;
		cursor: not-allowed;
	}

	.picker-val.disabled .edit-icon {
		opacity: 0.3;
	}

	.save-btn:disabled {
		background: linear-gradient(135deg, #c9d5ff, #b3c1ff);
		box-shadow: none;
		cursor: not-allowed;
	}

	.save-btn:disabled::after {
		display: none;
	}
</style>